package com.durian.ui.adapter.viewpager;

import android.content.Context;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import androidx.appcompat.app.AppCompatActivity;

import java.util.ArrayList;

/**
 * 说明：ViewPagerAdapter
 * <p/>
 * 作者：fanly
 * <p/>
 * 时间：2016/9/17 15:58
 * <p/>
 * 版本：version 1.0
 */
public class ViewPagerAdapter extends FragmentStatePagerAdapter {
    private ArrayList<ViewPageInfo> mInfos;
    private Context context;

    public static ViewPagerAdapter create(AppCompatActivity activity, Class[]clazz){
        return create(activity,null,clazz,null);
    }

    public static ViewPagerAdapter create(AppCompatActivity activity, String[]title, Class[]clazz, Bundle[]bundles){
        if (clazz == null){
            return null;
        }else {
            ArrayList<ViewPageInfo> infos = new ArrayList<>(clazz.length);
            for (int i = 0;i < clazz.length;i++){
                String tempTitle = null;
                Bundle tempBundle = null;
                if (title != null && title.length >= clazz.length){
                    tempTitle = title[i];
                }
                if (bundles != null && bundles.length >= clazz.length){
                    tempBundle = bundles[i];
                }
                ViewPageInfo info = new ViewPageInfo(tempTitle,clazz[i],tempBundle);
                infos.add(info);
            }
            return new ViewPagerAdapter(activity.getSupportFragmentManager(),activity,infos);
        }
    }

    public ViewPagerAdapter(FragmentManager fm, Context context) {
        this(fm,context,null);
    }

    public ViewPagerAdapter(FragmentManager fm, Context context, ArrayList<ViewPageInfo> infos) {
        super(fm);
        this.context = context;
        this.mInfos = (infos == null ? new ArrayList<ViewPageInfo>() : infos);
    }

    public ViewPagerAdapter addFragment(ViewPageInfo info){
        mInfos.add(info);
        return this;
    }

    public void refresh(ArrayList<ViewPageInfo> infos){
        if (infos != null){
            mInfos.clear();
            mInfos.addAll(infos);
            notifyDataSetChanged();
        }
    }

    @Override
    public Fragment getItem(int position) {
        ViewPageInfo info = mInfos.get(position);
        return Fragment.instantiate(context, info.clazz.getName(), info.params);
    }

    @Override
    public int getCount() {
        return mInfos.size();
    }

    @Override
    public int getItemPosition(Object object) {
        return PagerAdapter.POSITION_NONE;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mInfos.get(position).title;
    }

    public Fragment getFragment(ViewPager viewPager,int position){
        return (Fragment) instantiateItem(viewPager, position);
    }
}
